package com.weixing.mall.provider.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.model.domain.Param;
import com.weixing.mall.provider.model.dto.sys.LogAccessPwdDto;
import com.weixing.mall.provider.model.enums.sys.ParamCode;
import com.weixing.mall.provider.service.IParamService;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统参数配置
 *
 * @author Small
 * @since v2.0.1
 */
@RestController
@RequestMapping("/param")
public class ParamController extends BaseController {

    @Autowired
    private IParamService paramService;

    /**
     * 设置日志访问密码
     *
     * @param pwdDto 参数
     * @return  Result
     */
    @ApiOperation(value = "设置日志访问密码")
    @PostMapping("saveLogAccPwd")
    public Result saveLogAccPwd(@Validated  LogAccessPwdDto pwdDto){
        if (!pwdDto.getPwd().trim().equals(pwdDto.getConfirmPwd().trim())){
            return ResultUtil.error("两次密码输入不一致");
        }
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param_code", ParamCode.LOG_PWD.getValue());
        Param param = paramService.getOne(wrapper);
        if (null == param){
            Param paramNew = new Param();
            paramNew.setParamCode(ParamCode.LOG_PWD.getValue());
            paramNew.setParamValue(CommonUtil.encryptPassword(pwdDto.getPwd()));
            paramService.save(paramNew);
        }else{
            param.setParamValue(CommonUtil.encryptPassword(pwdDto.getPwd()));
            paramService.updateById(param);
        }
        return ResultUtil.success();
    }


    /**
     * 校验日志访问密码
     * @param pwd 访问密码
     * @return  Result
     */
    @PostMapping("checkLogAccPwd")
    public Result checkLogAccPwd( String  pwd){
        if (StringUtil.isEmpty(pwd.trim())){
            return ResultUtil.error("请输入访问密码");
        }
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param_code", ParamCode.LOG_PWD.getValue());
        Param param = paramService.getOne(wrapper);
        if (null == param){
           return ResultUtil.error("访问密码尚未设置，拒绝访问，请联系超级管理员");
        }else{
            boolean b = CommonUtil.bCryptCheck(pwd, param.getParamValue());
            if (!b){
                return ResultUtil.error("密码校验不通过，拒绝访问，请联系超级管理员");
            }
        }
        return ResultUtil.success();
    }
}
